<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace controller;

//use \PHPExcel_IOFactory as PHPExcel_IOFactory;

/**
 * Description of office
 *
 * @author Damian
 */
class Office extends Controller {
    public function getBasket($return=false){
         $session = \library\Registry::get("session");
        $shop = $session->get("shop");
        $basket = $session->get("basket");
        $order = $session->get("order");
        if (!$shop){
            $this->redirect("");
        }
        if (!$basket || !$order || !$order->AdressID || !$order->PaymentID || !$order->DeliveryMethodID || !$this->person){
             $this->redirect($this->shop->URL);
        }
        $productKeys = $basket->getProductKeys();
        $productsCriteria=  \model\TblProduct::getModel()->createCriteria($shop->ShopID)
                ->where(\model\TblProduct::ACTIVE, "=", 1,  \model\TblProduct::getModel()->getTable(), " and ")                
                ->in(\model\TblProduct::ID, $productKeys, \model\TblProduct::getModel()->getTable()," and ");
        $allProducts =\model\TblProduct::getModel()->all($productsCriteria);
        
        $products = $basket->getProducts();
        $view = $this->getActionView();
        $view->set("products", $products);
        $adressCriteria = new \model\Criteria();
        $adressCriteria->from(\model\TblAdress::getModel()->getTable())
                ->join(\model\TblPerson::getModel())
                ->join(\model\TblStreet::getModel())
                ->join(\model\TblCity::getModel())
                ->join(\model\TblPostCode::getModel())
                ->where(\model\TblPersonAdress::ADRESS_ID, "=", $order->AdressID, \model\TblAdress::getModel()->getTable());
        $adress = \model\TblPersonAdress::getModel()->first($adressCriteria);
        $delivery = \model\TblDeliveryMethod::getModel()->getByPrimaryKey($order->DeliveryMethodID);
        $payment = \model\TblPayment::getModel()->getByPrimaryKey($order->PaymentID);
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $phpWord->addTitleStyle(1, array('bold' => true, 'align' => 'center',"size"=>20));
        $phpWord->addTitleStyle(2, array('bold' => true, 'align' => 'center',"size"=>17));
        $section = $phpWord->addSection();
// Add first page header
        $header = $section->addHeader();
        $header->addText("zawartość koszyka sklepu " . $shop->Name);
// Add footer
        $footer = $section->addFooter();
        $footer->addPreserveText(htmlspecialchars('Strona {PAGE} z {NUMPAGES}.'), array('align' => 'center'));
        $footer->addText("Dokument wygenerowany automatycznie dla użytkownika " . $this->person->Name . " " . $this->person->Surname . "(" . $this->person->Email . ")");
        $section->addTextBreak();
        $section->addTitle("Podsumowanie produktów w koszyku",1);
        $styleTable = array('borderSize' => 6, 'borderColor' => '006699', 'cellMargin' => 80);
        $styleFirstRow = array('borderBottomSize' => 18, 'borderBottomColor' => '0000FF', 'bgColor' => '66BBFF');
        $styleCell = array('valign' => 'center');
        $fontStyle = array('bold' => true, 'align' => 'center');

        $phpWord->addTableStyle('Podsumowanie produktów w koszyku', $styleTable, $styleFirstRow);
        $phpWord->addTableStyle('Podsumowanie płatności i sposobu dostawy', $styleTable, $styleFirstRow);
        $table = $section->addTable('Podsumowanie produktów w koszyku');
        $table->addRow(900);
        $table->addCell(4000, $styleCell)->addText(htmlspecialchars("Twoje produkty"), $fontStyle);
        $table->addCell(4000, $styleCell)->addText(htmlspecialchars("Wartość"), $fontStyle);
        foreach ($products as $product) {
            $table->addRow();
            $table->addCell(4000)->addText(htmlspecialchars($product["Name"] . ", " . $product["Amount"] . " szt. po " . $product["Price"] . " zł za sztukę"));
            $table->addCell(4000)->addText(htmlspecialchars($product["Cost"] . " zł"));
        }
        $table->addRow();
        $table->addCell(4000)->addText(htmlspecialchars(" Podsumowanie Koszyka"), $fontStyle);
        $table->addCell(4000)->addText(htmlspecialchars("Łącznie: {$basket->getItemCount()} szt. za kwotę {$basket->getTotalCost()} zł"), $fontStyle);
        $section->addTextBreak(3);
        //płatność i adres
        $table2 = $section->addTable('Podsumowanie płatności i sposobu dostawy');
        $table2->addRow(900);
        $table2->addCell(4000, $styleCell)->addText(htmlspecialchars("Rodzaj płatności"), $fontStyle);
        $table2->addCell(4000, $styleCell)->addText(htmlspecialchars("Sposób Dostawy"), $fontStyle);
        $table2->addRow();
        $table2->addCell(4000)->addText(htmlspecialchars($payment->Name), $fontStyle);
        $table2->addCell(4000)->addText(htmlspecialchars("{$delivery->Name}, cena: {$delivery->Price}"), $fontStyle);
        $table2->addRow();
        $table2->addCell(4000)->addText(htmlspecialchars( $payment->Description), $fontStyle);
        $table2->addCell(4000)->addText(htmlspecialchars($delivery->Description), $fontStyle);
        $section->addTextBreak();
        $section->addText(htmlspecialchars('Zamówienie zostanie wysłane na adres'));
        $section->addText(htmlspecialchars("{$adress->PostCodeID->Code}, {$adress->CityID->Name}"));
        $section->addText(htmlspecialchars("{$adress->StreetID->Name} {$adress->Number}"));
        
        foreach ($allProducts as $product){
            $section->addPageBreak();
            $section->addTitle($product->ProductID->Name,1);
            if ($product->ProductID->AvgMark!=-1){
                 $section->addText("Średnia ocena: ".$product->ProductID->AvgMark);
            }
            $section->addTitle("Opis produktu",2);
            $section->addText($product->ProductID->ShortDescription);
            $section->addText($product->ProductID->Description);
            $section->addText("Producent: ".$product->ProductID->ManufacturerID->Name);
            $section->addText("Kategoria: ".$product->ProductID->CategoryID->Name);
            $section->addTitle("Galeria produktu",2);
            $picturesCriteria = new \model\Criteria();
            $picturesCriteria->from(\model\TblProductPicture::getModel()->getTable())
                ->join(\model\TblPicture::getModel())
                ->where(\model\TblProductPicture::PRODUCT_ID, "=", $product->ProductID->ProductID, \model\TblProductPicture::getModel()->getTable());
            $pictures = \model\TblPicture::getModel()->all($picturesCriteria);
            foreach ($pictures as $picture){
                $section->addImage('img/'.substr($shop->URL,0,strlen($shop->URL)-1)."/800px/".$picture->PictureID->Name, array('width' => 250));
            }           
        }
        if ($return){
            return $phpWord;
        }
        // Save File
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $filename = "zawartość koszyka sklepu " . $shop->Name.".docx";
        $objWriter->save($filename);

        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . $filename);
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filename));
        flush();
        readfile($filename);
        unlink($filename); // deletes the temporary file
    }

    public function category() {
         $session = \library\Registry::get("session");
        $shop = $session->get("shop");
        $category = $session->get("category");
        if (!$category) {
            $this->redirect($this->shop->URL);
            exit;
        }
        $IDs = $category->getAllIds();
        $productsCriteria = \model\TblProduct::getModel()->createCriteria($this->shop->ShopID)
                ->where(\model\TblProduct::ACTIVE, "=", 1, \model\TblProduct::getModel()->getTable(), " and ")
                ->in(\model\TblProduct::CATEGORY_ID, $IDs, \model\TblCategory::getModel()->getTable(), " and ");
        $Products = \model\TblProduct::getModel()->all($productsCriteria);
        $objPHPExcel = new \model\MyExcelDocument($this->person, $this->shop);
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("produkty - " . $category->Name);
        $objPHPExcel->getActiveSheet()->setCellValue('A1', "Nazwa produktu");
        $objPHPExcel->getActiveSheet()->setCellValue('B1', "Cena brutto");
        $objPHPExcel->getActiveSheet()->setCellValue('C1', "Stawka VAT");
        $objPHPExcel->getActiveSheet()->setCellValue('D1', "Producent");
        $objPHPExcel->getActiveSheet()->setCellValue('E1', "Opis skrócony");
        $objPHPExcel->getActiveSheet()->setCellValue('F1', "Średnia ocena");
        $objPHPExcel->getActiveSheet()->setCellValue('G1', "Dostępność");
        $objPHPExcel->getActiveSheet()->getColumnDimension("A")->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension("B")->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension("C")->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension("D")->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension("E")->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension("F")->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension("G")->setWidth(20);
        $objPHPExcel->getActiveSheet()->getStyle('B1:B1000')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_PLN);
        $objPHPExcel->getActiveSheet()->getStyle('c1:C1000')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE);
        $objPHPExcel->getActiveSheet()->getStyle('E1:E1000')->getAlignment()->setWrapText(true);
        $objPHPExcel->getActiveSheet()->freezePane('A2');
        $index = 2;
        foreach ($Products as $Product) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $index, $Product->ProductID->Name);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $index, $Product->ProductID->GrossPrice);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $index, $Product->ProductID->VAT / 100);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $index, $Product->ProductID->ManufacturerID->Name);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $index, $Product->ProductID->ShortDescription);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $index, ($Product->ProductID->AvgMark == -1) ? "Brak oceny" : $Product->ProductID->AvgMark);
            $objPHPExcel->getActiveSheet()->setCellValue('g' . $index, $Product->ProductID->Amount . " szt.");
            $index++;
        }
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->save($category->Name . " - lista produktów");
    }

    public function manufacturer() {
        $session = \library\Registry::get("session");
        $manufacturer = $session->get("manufacturer");
        $objPHPExcel = new \model\MyExcelDocument($this->person, $this->shop);
        $productsCriteria = new \model\Criteria();
        if (!$manufacturer) {
            $productsCriteria = \model\TblProduct::getModel()->createCriteria($this->shop->ShopID)->where(\model\TblProduct::ACTIVE, "=", 1, false, " and ");
            $objPHPExcel->getActiveSheet()->setTitle("wszystkie produkty");
        } else {
            $productsCriteria = \model\TblProduct::getModel()->createCriteria($this->shop->ShopID)->where(\model\TblProduct::ACTIVE, "=", 1, false, " and ")
                    ->where(\model\TblProduct::MANUFACTURER_ID, "=", $manufacturer->ManufacturerID, \model\TblManufacturer::getModel()->getTable(), " and ");
            $objPHPExcel->getActiveSheet()->setTitle("produkty - " . $manufacturer->Name);
        }
        $Products = \model\TblProduct::getModel()->all($productsCriteria);

        $objPHPExcel->setActiveSheetIndex(0);

        $objPHPExcel->getActiveSheet()->setCellValue('A1', "Nazwa produktu");
        $objPHPExcel->getActiveSheet()->setCellValue('B1', "Cena brutto");
        $objPHPExcel->getActiveSheet()->setCellValue('C1', "Stawka VAT");
        $objPHPExcel->getActiveSheet()->setCellValue('D1', "Kategoria");
        $objPHPExcel->getActiveSheet()->setCellValue('E1', "Opis skrócony");
        $objPHPExcel->getActiveSheet()->setCellValue('F1', "Średnia ocena");
        $objPHPExcel->getActiveSheet()->setCellValue('G1', "Dostępność");
        $objPHPExcel->getActiveSheet()->getColumnDimension("A")->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension("B")->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension("C")->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension("D")->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension("E")->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension("F")->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension("G")->setWidth(20);
        $objPHPExcel->getActiveSheet()->getStyle('B1:B1000')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_PLN);
        $objPHPExcel->getActiveSheet()->getStyle('c1:C1000')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE);
        $objPHPExcel->getActiveSheet()->getStyle('E1:E1000')->getAlignment()->setWrapText(true);
        $objPHPExcel->getActiveSheet()->freezePane('A2');
        $index = 2;
        foreach ($Products as $Product) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $index, $Product->ProductID->Name);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $index, $Product->ProductID->GrossPrice);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $index, $Product->ProductID->VAT / 100);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $index, $Product->ProductID->CategoryID->Name);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $index, $Product->ProductID->ShortDescription);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $index, ($Product->ProductID->AvgMark == -1) ? "Brak oceny" : $Product->ProductID->AvgMark);
            $objPHPExcel->getActiveSheet()->setCellValue('g' . $index, $Product->ProductID->Amount . " szt.");
            $index++;
        }
        $objPHPExcel->setActiveSheetIndex(0);
        if (!$manufacturer) {
            $objPHPExcel->save($this->shop->Name.", wszyscy producenci - lista produktów");
        } else {
            $objPHPExcel->save($this->shop->Name.", ".$manufacturer->Name . " - lista produktów");
        }
    }
    public function productData(){
                $session = \library\Registry::get("session");
                $shop = $session->get("shop");
                $id = \library\RequestMethods::get("id");
        $productsCriteria=  \model\TblProduct::getModel()->createCriteria($shop->ShopID)
                ->where(\model\TblProduct::ACTIVE, "=", 1,  \model\TblProduct::getModel()->getTable(), " and ")                
                ->where(\model\TblProduct::ID, "=", $id, \model\TblProduct::getModel()->getTable()," and ");
        $allProducts =\model\TblProduct::getModel()->all($productsCriteria);        
        
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $phpWord->addTitleStyle(1, array('bold' => true, 'align' => 'center',"size"=>20));
        $phpWord->addTitleStyle(2, array('bold' => true, 'align' => 'center',"size"=>17));
        $section = $phpWord->addSection();
// Add first page header
// Add footer
        $footer = $section->addFooter();
        $footer->addPreserveText(htmlspecialchars('Strona {PAGE} z {NUMPAGES}.'), array('align' => 'center'));
//        var_dump($this);
        if ($this->person){
            $footer->addText("Dokument wygenerowany automatycznie dla użytkownika " . $this->person->Name . " " . $this->person->Surname . "(" . $this->person->Email . ")");
        }
        else {
            $footer->addText("Dokument wygenerowany automatycznie ");
        }
        $section->addTextBreak();
        $section->addTitle("Podsumowanie produktów w koszyku",1);     
        foreach ($allProducts as $product){
            $section->addTitle($product->ProductID->Name,1);
            if ($product->ProductID->AvgMark!=-1){
                 $section->addText("Średnia ocena: ".$product->ProductID->AvgMark);
            }
            $section->addTitle("Opis produktu",2);
            $section->addText($product->ProductID->ShortDescription);
            $section->addText($product->ProductID->Description);
            $section->addText("Producent: ".$product->ProductID->ManufacturerID->Name);
            $section->addText("Kategoria: ".$product->ProductID->CategoryID->Name);
            $section->addTitle("Galeria produktu",2);
            $picturesCriteria = new \model\Criteria();
            $picturesCriteria->from(\model\TblProductPicture::getModel()->getTable())
                ->join(\model\TblPicture::getModel())
                ->where(\model\TblProductPicture::PRODUCT_ID, "=", $product->ProductID->ProductID, \model\TblProductPicture::getModel()->getTable());
            $pictures = \model\TblPicture::getModel()->all($picturesCriteria);
            foreach ($pictures as $picture){
                $section->addImage('img/'.substr($shop->URL,0,strlen($shop->URL)-1)."/800px/".$picture->PictureID->Name, array('width' => 250));
            }          
        }

        // Save File
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $filename = $shop->Name." - dane produktu " . $product->ProductID->Name.".docx";
        $objWriter->save($filename);

        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . $filename);
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filename));
        flush();
        readfile($filename);
        unlink($filename); //
    }

}
